<?php

class Reportes_ConsOnlineController extends Zend_Controller_Action
{
    /**
     * 
     * @var Zend_Auth_Storage_Interface
     */
    private $_user_info;
    /**
     * 
     * @var Zwei_Admin_Acl
     */
    private $_acl;
    /**
     * 
     * @var string
     */
    private $_page;

    public function init()
    {
        $this->_helper->layout()->disableLayout();
        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_user_info = Zend_Auth::getInstance()->getStorage()->read();
            $this->_acl = new Zwei_Admin_Acl($this->_user_info->user_name);
            $this->_page = "reportes/cons-online";
            if (!$this->_acl->isUserAllowed($this->_page)) exit("<p>Acceso denegado a $this->_page</p>"); 
        } else {
            $this->_redirect('index/login');
        }
    }

    public function indexAction()
    {

        include_once ROOT_DIR. "/classes/cliente-class.php";
        include_once ROOT_DIR. "/classes/class_xml.php";


        //error_reporting(E_ALL);

        echo "<script src='".BASE_URL."js/funciones.js'></script>";
        // echo "<link rel=STYLESHEET type=text/css href=../css/calendar.css>";
        // echo "<script language=JavaScript src=../libs/simplecalendar.js type=text/javascript></script>";

        global $titleColor;
        global $blankColor;
        global $grayColor;

        global $_img_ok;

        $ok_image = $_img_ok;

        global $urlServerXML;
        $url = $urlServerXML;
         
        # Titulo
        echo "<h2>Consulta en L&iacute;nea</h2>";

        $form = new HTML_Form(BASE_URL.'reportes/cons-online','get','myform','ifrm_process');
        echo $form->returnStart()."\n";
        $fila=0;

        $tableAttrs = array('border' => "0",
                    'cellspacing' => "0",
                    'align' => "center",
                    'class' => "",
            'width' => "20%");

        $table = new HTML_Table($tableAttrs);
        $titleStyle = array('colspan' => "5");
        $blankStyle = array('colspan' => "5");
        $rowStyle   = array('align' => "left");

        //Buscar por MSISDN
        $row = array("<p>MSISDN</p>",
        $form->returnText("msisdn", @$_REQUEST["msisdn"], 13, 15," dojoType=\"dijit.form.ValidationTextBox\""),
             "",
        $form->returnHidden('p',@$_REQUEST['p'],''),
"" ,
        $form->returnSubmit("Consultar","consultar","class='boton2' "),
"",
        );

        $table->addRow($row,$rowStyle);
        $table->updateCellAttributes($fila, 1, array('valign' => "center"));


        $fila++;
        $table->display();

        echo "<br>";

        if(isset($_REQUEST["consultar"]) && $_REQUEST["consultar"] == "Consultar")
        {
            $requests = "?";
            foreach ($_REQUEST as $i => $v) {
                $requests .= "&$i=$v";
            }

            if (!isset($_REQUEST['norepost'])) {

                echo "<script>window.parent.cargarPanelCentral('/reportes/cons-online$requests&norepost=1'); </script>";
            }
            $cliente = new CLIENTE( $_REQUEST["msisdn"], "", "" );

            $cliente->get_online();

            if(count($cliente->elementos) != 0)
            {

                //echo"====D<br>";print_r($cliente->elementos);echo "<br>";
                #--- Parametros generales para las tablas usuarios y campaanas
                $tableUsuCamp = array('border' => "0",
                          'cellspacing' => "0",
                          'align' => "center",
                          'class' => "borde3",
                          'width' => "82%");

                $titleStyle = array('align' => "left");
                $blankStyle = array('align' => "left");
                $rowStyle   = array('align' => "left");
                #---


                $table = new HTML_Table($tableUsuCamp);
                if (array_key_exists("msg", $_REQUEST))
                $msg = $_REQUEST["msg"];
                else
                $msg = "&nbsp;";

                $msgStyle = array('align' => "center", 'bgcolor' => $blankColor);
                $msgRow = array("<font class='textoAzul'>$msg</font>");

                $row = array(
                 "<label class=SUBT>Promocion</label>",
         "<label class=SUBT>Fecha Compra</label>",
         "<label class=SUBT>Fecha Expiracion</label>",
         "<label class=SUBT>Recurrente</label>",
         "<label class=SUBT>Bolsa</label>",
         "<label class=SUBT>Unidad</label>",
         "<label class=SUBT>Cantidad</label>"
         //"<label class=SUBT>Saldo</label>",
                //"<label class=SUBT>Activar</label>",
                //"<label class=SUBT>Eliminar</label>"
                );

                $editable = true;//Zwei_Admin_Acl::isActionAllowed( "EDIT" );
                $removible =  true;//Zwei_Admin_Acl::isActionAllowed( "DELETE" );
                if ( $editable )
                $row[]="<label class=SUBT>Activar</label>";
                if($removible )
                $row[]="<label class=SUBT>Eliminar</label>";

                $table->addRow($row,$titleStyle);

                $fila = 0;
                $i = 1;

                $table->updateCellAttributes($fila,0,array('width' => "15%"));
                $table->updateCellAttributes($fila,1,array('width' => "15%"));
                $table->updateCellAttributes($fila,2,array('width' => "15%"));
                $table->updateCellAttributes($fila,3,array('width' => "10%"));
                $table->updateCellAttributes($fila,4,array('width' => "10%"));
                $table->updateCellAttributes($fila,5,array('width' => "10%"));
                $table->updateCellAttributes($fila,6,array('width' => "10%"));
                if ($editable)
                $table->updateCellAttributes($fila,7,array('width' => "5%"));
                if ($removible)
                $table->updateCellAttributes($fila,8,array('width' => "5%"));


                foreach ($cliente->elementos as $key => $value)
                {
                    foreach( $value["bolsas"] as $key => $bolsa )
                    {
                        // $activar = $form->returnImage("elim", $elimina_image, "border=0 alt='eliminar' title='Eliminar'
                        //                                  onClick='ConfirmarActivarBolsa(\"{$value->id_promo}\")'");
                        $activar = $form->returnImage("activar", $ok_image, "border=0 alt='activar' title='Pegar Bolsa'    onClick='ConfirmarActivarBolsa(\"$bolsa[0]\", \"$bolsa[1]\")'");

                        if( $value[1] == 0 )
                        {
                            $recurrencia = "No";
                            $eliminar = "-";
                        }
                        else
                        {
                            $recurrencia = "Si";
                            $msisdn = $_REQUEST["msisdn"];
                            $eliminar = $form->returnImage("eliminar", $_img_delete, "border=0 alt='eliminar' title='Eliminar Recurrencia' onClick='ConfirmarEliminarPromo(\"$value[0]\", \"$msisdn\")'");
                        }


                        $rowBolsa = array(
            "<label class=textoAzul>{$bolsa[0]}</label>",
            "<label class=textoAzul>{$bolsa[1]}</label>",
            "<label class=textoAzul>{$bolsa[2]}</label>"
                        );

                        if ( $editable )
                        $rowBolsa[]=$activar;
                        if($removible )
                        $rowBolsa[]=$eliminar;

                        $row = array(
            "<label class=SUBT>{$value[0]}</label>",
            "<label class=textoAzul>{$value[2]}</label>", 
            "<label class=textoAzul>{$value[3]}</label>",
            "<label class=textoAzul>{$recurrencia}</label>",
                        $rowBolsa
                        );

                        $fila++;

                        if ($fila == 0 || ($fila%2) == 0)
                        $table->addRow($row, $rowStyle);
                        else
                        $table->addRow($row, $blankStyle);

                    }

                    $table->updateCellAttributes($i, 0, array('rowspan' => count($value["bolsas"])));
                    $table->updateCellAttributes($i, 1, array('rowspan' => count($value["bolsas"])));
                    $i++;

                }

                $table->display();
                echo "<br>";

                // Consultar el saldo
                $xmlcontent = "<?xml version='1.0'  encoding='ISO-8859-1'?>";
                $xmlcontent .= "<msg>";
                $xmlcontent .= "<header id_trans='1111' app='xml' user='web' passw='web' action='1'/>";
                $xmlcontent .= "<req>";
                $xmlcontent .= "<op>req_cons_saldo</op>";
                $xmlcontent .= "<msisdn>".$_REQUEST["msisdn"]."</msisdn>";
                $xmlcontent .= "</req>";
                $xmlcontent .= "</msg>";


                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
                curl_setopt($ch, CURLOPT_VERBOSE, 0);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlcontent);

                $result = curl_exec($ch);
                if (curl_errno($ch))
                {
                    // echo "ERROR";
                }
                else
                {
                    $sms_onnet = -1;
                    $sms_td = -1;
                    $mms_onnet = -1;
                    $mms_td = -1;
                    $kb = -1;
                    $spinvox = -1;
                    $minutos = -1;

                    if( $this->procesaXML($result, $sms_onnet, $sms_td, $mms_onnet, $mms_td, $kb, $spinvox, $minutos) )
                    {
                        if( $sms_onnet >= 0 || $sms_td >= 0 ||  $mms_onnet>=0 || $mms_td>=0 || $kb>=0 || $spinvox>=0 || $minutos>=0 )
                        {
                            $tableSaldo = array('border' => "0",
                          'cellspacing' => "0",
                          'align' => "center",
                          'class' => "borde3",
                          'width' => "20%");

                            $titleStyle = array('align' => "center", 'bgcolor' => $titleColor);
                            $blankStyle = array('align' => "center", 'bgcolor' => $blankColor, 'border'=>'1', 'class' => "borde3");
                            $rowStyle   = array('align' => "left", 'bgcolor' => $grayColor);

                            $table = new HTML_Table($tableSaldo);

                            $row = array(
                 "<label class=SUBT>Bolsa</label>",
                 "<label class=SUBT>Saldo</label>"
                 );

                 $table->addRow($row,$titleStyle);

                 $fila = 0;

                 $table->updateCellAttributes($fila,0,array('width' => "20%"));
                 $table->updateCellAttributes($fila,1,array('width' => "20%"));

                 if( $sms_onnet >= 0)
                 {
                     $row = array(
             "<label class=textoAzul>SMS Movistar</label>",
                     "<label class=textoAzul>{$sms_onnet}</label>"
                     );
                     $table->addRow($row, $blankStyle);

                 }
                 if( $sms_td >= 0)
                 {
                     $row = array(
                     "<label class=textoAzul>SMS TD</label>",
                     "<label class=textoAzul>{$sms_td}</label>"
                     );
                     $table->addRow($row, $blankStyle);

                 }
                 if( $mms_onnet >= 0)
                 {
                     $row = array(
                     "<label class=textoAzul>MMS Movistar</label>",
                     "<label class=textoAzul>{$mms_onnet}</label>"
                     );
                     $table->addRow($row, $blankStyle);

                 }
                 if( $mms_td >= 0)
                 {
                     $row = array(
                     "<label class=textoAzul>MMS TD</label>",
                     "<label class=textoAzul>{$mms_td}</label>"
                     );
                     $table->addRow($row, $blankStyle);

                 }
                 if( $kb >= 0)
                 {
                     $row = array(
                     "<label class=textoAzul>KB</label>",
                     "<label class=textoAzul>{$kb}</label>"
                     );
                     $table->addRow($row, $blankStyle);

                 }
                 if( $spinvox >= 0)
                 {
                     $row = array(
                     "<label class=textoAzul>Spinvox</label>",
                     "<label class=textoAzul>{$spinvox}</label>"
                     );
                     $table->addRow($row, $blankStyle);

                 }
                 if( $minutos >= 0)
                 {
                     $row = array(
                     "<label class=textoAzul>Minutos</label>",
                     "<label class=textoAzul>{$minutos}</label>"
                     );
                     $table->addRow($row, $blankStyle);

                 }



                 $table->display();
                        }
                    }

                }
                curl_close($ch);


                echo $form->returnEnd()."\n";
                echo "<br/><center><input type=\"button\" value=\"Exportar a Excel\" onClick=\"excelConsOnline('{$_REQUEST['msisdn']}')\"></center>";
            }
            else
            echo "<br><br><br><br><p class=SUBT align=center>No existen registros</p>";
        }
    }

    function procesaXML($result, &$sms_onnet, &$sms_td, &$mms_onnet, &$mms_td, &$kb, &$spinvox, &$minutos)
    {
        $xml = new SimpleXMLElementExtended($result);
        if( !is_object($xml) )
        {
            echo "Error XML";
            return false;
        }

        if( (string)$xml->resp->result == 0 )
        {
            foreach ($xml->resp->bolsas->children() as $key=>$value)
            {
                //echo $key." - ".$value."\n";
                if( $key == "sms_onnet")
                $sms_onnet = $value;
                else if( $key == "sms_td")
                $sms_td = $value;
                else if( $key == "mms_onnet")
                $mms_onnet = $value;
                else if( $key == "mms_td")
                $mms_td = $value;
                else if( $key == "kb")
                $kb = $value;
                else if( $key == "spinvox")
                $spinvox = $value;
                else if( $key == "minutos")
                $minutos = $value;
            }
            return true;

        }
        else
        return false;
    }

    public function blAction()
    {
        // action body
    }

    public function excelAction()
    {
        include_once ROOT_DIR. "/classes/cliente-class.php";
        $cliente = new CLIENTE( $_REQUEST["msisdn"], "", "" );
        $cliente->get_online();
        $rowset = $cliente->elementos;

        //Debug::write($rowset);
        $i = 0;
        foreach ($cliente->elementos as $key => $value)
        {
            $bolsas = array();
            foreach ($value["bolsas"] as $key => $bolsa)
            {
                $bolsas[] = $bolsa[0];           
            }
            $rowset[$i]["bolsas"] = implode(", ", $bolsas); 
        }
        $i++;
 
        
        header('Content-type: application/vnd.ms-excel');
        header("Content-Disposition: attachment; filename=cons-online.xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        $table = new Zwei_Utils_Table();
        echo $table->rowsetToHtml($rowset, array("Promoci&oacute;n", "Recurrencia", "Fecha Compra", "Fecha Expiración", "Bolsas"));
     
    }
}